// (c) Original Source from http://stringtopathgeometry.codeplex.com/
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Windows;
using System.Windows.Media;

// ReSharper disable CheckNamespace
namespace DevPhone.Controls
// ReSharper restore CheckNamespace
{
    public static class StringPathGeometry
    {
        #region Const & Private Variables

        const bool AllowSign = true;
        const bool AllowComma = true;
        const bool IsFilled = true;
        const bool IsClosed = true;

        static PathFigure _figure;     // Figure object, which will accept parsed segments
        static string _pathString;     // Input string to be parsed
        static int _pathLength;
        static int _curIndex;          // Location to read next character from
        static bool _figureStarted;    // StartFigure is effective 

        static Point _lastStart;       // Last figure starting point
        static Point _lastPoint;       // Last point 
        static Point _secondLastPoint; // The point before last point

        static char _token;            // Non whitespace character returned by ReadToken

        #endregion

        #region Public Functionality

        /// <summary>
        /// Main conversion routine - converts string path data definition to PathGeometry object
        /// </summary>
        /// <param name="path">String with path data definition</param>
        /// <returns>PathGeometry object created from string definition</returns>
        public static PathGeometry Convert(string path)
        {
            if (null == path)
                throw new ArgumentException("Path string cannot be null!");

            if (path.Length == 0)
                throw new ArgumentException("Path string cannot be empty!");

            return Parse(path);
        }

        #endregion

        #region Private Functionality

        /// <summary>
        /// Main parser routine, which loops over each char in received string, and performs actions according to command/parameter being passed
        /// </summary>
        /// <param name="path">String with path data definition</param>
        /// <returns>PathGeometry object created from string definition</returns>
        [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "parse logic")]
        private static PathGeometry Parse(string path)
        {
            PathGeometry pathGeometry = null;

            _pathString = path;
            _pathLength = path.Length;
            _curIndex = 0;

            _secondLastPoint = new Point(0, 0);
            _lastPoint = new Point(0, 0);
            _lastStart = new Point(0, 0);

            _figureStarted = false;

            var first = true;
            var lastCmd = ' ';

            while (ReadToken()) // Empty path is allowed in XAML
            {
                var cmd = _token;
                if (first)
                {
                    if ((cmd != 'M') && (cmd != 'm') && (cmd != 'f') && (cmd != 'F'))  // Path starts with M|m 
                    {
                        ThrowBadToken();
                    }
                    first = false;
                }

                switch (cmd)
                {
                    case 'f':
                    case 'F':
                        pathGeometry = new PathGeometry();
                        var num = ReadNumber(!AllowComma);
                        pathGeometry.FillRule = num.Equals(0) ? FillRule.EvenOdd : FillRule.Nonzero;
                        break;
                    case 'm':
                    case 'M':
                        // XAML allows multiple points after M/m
                        _lastPoint = ReadPoint(cmd, !AllowComma);
                        _figure = new PathFigure { StartPoint = _lastPoint, IsFilled = IsFilled, IsClosed = !IsClosed };
                        _figureStarted = true;
                        _lastStart = _lastPoint;
                        lastCmd = 'M';
                        while (IsNumber(AllowComma))
                        {
                            _lastPoint = ReadPoint(cmd, !AllowComma);
                            var lineSegment = new LineSegment { Point = _lastPoint };
                            _figure.Segments.Add(lineSegment);
                            lastCmd = 'L';
                        }
                        break;
                    case 'l':
                    case 'L':
                    case 'h':
                    case 'H':
                    case 'v':
                    case 'V':
                        EnsureFigure();
                        do
                        {
                            switch (cmd)
                            {
                                case 'l': _lastPoint = ReadPoint(cmd, !AllowComma); break;
                                case 'L': _lastPoint = ReadPoint(cmd, !AllowComma); break;
                                case 'h': _lastPoint.X += ReadNumber(!AllowComma); break;
                                case 'H': _lastPoint.X = ReadNumber(!AllowComma); break;
                                case 'v': _lastPoint.Y += ReadNumber(!AllowComma); break;
                                case 'V': _lastPoint.Y = ReadNumber(!AllowComma); break;
                            }
                            var lineSegment = new LineSegment { Point = _lastPoint };
                            _figure.Segments.Add(lineSegment);
                        }
                        while (IsNumber(AllowComma));
                        lastCmd = 'L';
                        break;
                    case 'c':
                    case 'C': // cubic Bezier 
                    case 's':
                    case 'S': // smooth cublic Bezier
                        EnsureFigure();
                        do
                        {
                            Point p;
                            if ((cmd == 's') || (cmd == 'S'))
                            {
                                p = lastCmd == 'C' ? Reflect() : _lastPoint;
                                _secondLastPoint = ReadPoint(cmd, !AllowComma);
                            }
                            else
                            {
                                p = ReadPoint(cmd, !AllowComma);
                                _secondLastPoint = ReadPoint(cmd, AllowComma);
                            }
                            _lastPoint = ReadPoint(cmd, AllowComma);
                            var bizierSegment = new BezierSegment { Point1 = p, Point2 = _secondLastPoint, Point3 = _lastPoint };
                            _figure.Segments.Add(bizierSegment);
                            lastCmd = 'C';
                        }
                        while (IsNumber(AllowComma));
                        break;
                    case 'q':
                    case 'Q': // quadratic Bezier 
                    case 't':
                    case 'T': // smooth quadratic Bezier
                        EnsureFigure();
                        do
                        {
                            if ((cmd == 't') || (cmd == 'T'))
                            {
                                _secondLastPoint = lastCmd == 'Q' ? Reflect() : _lastPoint;

                                _lastPoint = ReadPoint(cmd, !AllowComma);
                            }
                            else
                            {
                                _secondLastPoint = ReadPoint(cmd, !AllowComma);
                                _lastPoint = ReadPoint(cmd, AllowComma);
                            }
                            var quadraticBezierSegment = new QuadraticBezierSegment { Point1 = _secondLastPoint, Point2 = _lastPoint };
                            _figure.Segments.Add(quadraticBezierSegment);
                            lastCmd = 'Q';
                        }
                        while (IsNumber(AllowComma));
                        break;
                    case 'a':
                    case 'A':
                        EnsureFigure();
                        do
                        {
                            // A 3,4 5, 0, 0, 6,7
                            double w = ReadNumber(!AllowComma);
                            double h = ReadNumber(AllowComma);
                            double rotation = ReadNumber(AllowComma);
                            var large = ReadBool();
                            var sweep = ReadBool();
                            _lastPoint = ReadPoint(cmd, AllowComma);
                            var arcSegment = new ArcSegment
                                                 {
                                                     Point = _lastPoint,
                                                     Size = new Size(w, h),
                                                     RotationAngle = rotation,
                                                     IsLargeArc = large,
                                                     SweepDirection =
                                                         sweep
                                                             ? SweepDirection.Clockwise
                                                             : SweepDirection.Counterclockwise
                                                 };
                            _figure.Segments.Add(arcSegment);
                        }
                        while (IsNumber(AllowComma));
                        lastCmd = 'A';
                        break;
                    case 'z':
                    case 'Z':
                        EnsureFigure();
                        _figure.IsClosed = IsClosed;
                        _figureStarted = false;
                        lastCmd = 'Z';
                        _lastPoint = _lastStart; // Set reference point to be first point of current figure
                        break;
                    default:
                        ThrowBadToken();
                        break;
                }
            }

            if (null != _figure)
            {
                if (null == pathGeometry)
                    pathGeometry = new PathGeometry();
                pathGeometry.Figures.Add(_figure);
            }
            return pathGeometry;
        }

        private static void SkipDigits(bool signAllowed)
        {
            // Allow for a sign 
            if (signAllowed && More() && ((_pathString[_curIndex] == '-') || _pathString[_curIndex] == '+'))
            {
                _curIndex++;
            }
            while (More() && (_pathString[_curIndex] >= '0') && (_pathString[_curIndex] <= '9'))
            {
                _curIndex++;
            }
        }

        private static bool ReadBool()
        {
            SkipWhiteSpace(AllowComma);
            if (More())
            {
                _token = _pathString[_curIndex++];
                if (_token == '0')
                {
                    return false;
                }
                if (_token == '1')
                {
                    return true;
                }
            }
            ThrowBadToken();
            return false;
        }

        private static Point Reflect()
        {
            return new Point(2 * _lastPoint.X - _secondLastPoint.X,
                             2 * _lastPoint.Y - _secondLastPoint.Y);
        }

        private static void EnsureFigure()
        {
            if (!_figureStarted)
            {
                _figure = new PathFigure { StartPoint = _lastStart };
                _figureStarted = true;
            }
        }

        private static double ReadNumber(bool allowComma)
        {
            if (!IsNumber(allowComma))
            {
                ThrowBadToken();
            }
            var simple = true;
            var start = _curIndex;
            //
            // Allow for a sign
            //
            // There are numbers that cannot be preceded with a sign, for instance, -NaN, but it's 
            // fine to ignore that at this point, since the CLR parser will catch this later.
            // 
            if (More() && ((_pathString[_curIndex] == '-') || _pathString[_curIndex] == '+'))
            {
                _curIndex++;
            }
            // Check for Infinity (or -Infinity).
            if (More() && (_pathString[_curIndex] == 'I'))
            {
                // 
                // Don't bother reading the characters, as the CLR parser will 
                // do this for us later.
                // 
                _curIndex = Math.Min(_curIndex + 8, _pathLength); // "Infinity" has 8 characters
                simple = false;
            }
                // Check for NaN 
            else if (More() && (_pathString[_curIndex] == 'N'))
            {
                // 
                // Don't bother reading the characters, as the CLR parser will
                // do this for us later. 
                //
                _curIndex = Math.Min(_curIndex + 3, _pathLength); // "NaN" has 3 characters
                simple = false;
            }
            else
            {
                SkipDigits(!AllowSign);
                // Optional period, followed by more digits 
                if (More() && (_pathString[_curIndex] == '.'))
                {
                    simple = false;
                    _curIndex++;
                    SkipDigits(!AllowSign);
                }
                // Exponent
                if (More() && ((_pathString[_curIndex] == 'E') || (_pathString[_curIndex] == 'e')))
                {
                    simple = false;
                    _curIndex++;
                    SkipDigits(AllowSign);
                }
            }
            if (simple && (_curIndex <= (start + 8))) // 32-bit integer
            {
                var sign = 1;

                if (_pathString[start] == '+')
                {
                    start++;
                }
                else if (_pathString[start] == '-')
                {
                    start++;
                    sign = -1;
                }
                var value = 0;
                while (start < _curIndex)
                {
                    value = value * 10 + (_pathString[start] - '0');
                    start++;
                }
                return value * sign;
            }
            var subString = _pathString.Substring(start, _curIndex - start);
            try
            {
                return System.Convert.ToDouble(subString,CultureInfo.InvariantCulture);
            }
            catch (FormatException except)
            {
                throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Unexpected character in path '{0}' at position {1}", _pathString, _curIndex - 1), except);
            }
        }

        private static bool IsNumber(bool allowComma)
        {
            var commaMet = SkipWhiteSpace(allowComma);
            if (More())
            {
                _token = _pathString[_curIndex];
                // Valid start of a number
                if ((_token == '.') || (_token == '-') || (_token == '+') || ((_token >= '0') && (_token <= '9'))
                    || (_token == 'I')  // Infinity
                    || (_token == 'N')) // NaN 
                {
                    return true;
                }
            }
            if (commaMet) // Only allowed between numbers
            {
                ThrowBadToken();
            }
            return false;
        }

        private static Point ReadPoint(char cmd, bool allowcomma)
        {
            var x = ReadNumber(allowcomma);
            var y = ReadNumber(AllowComma);
            if (cmd >= 'a') // 'A' < 'a'. lower case for relative
            {
                x += _lastPoint.X;
                y += _lastPoint.Y;
            }
            return new Point(x, y);
        }

        private static bool ReadToken()
        {
            SkipWhiteSpace(!AllowComma);
            // Check for end of string 
            if (More())
            {
                _token = _pathString[_curIndex++];
                return true;
            }
            return false;
        }

        private static bool More()
        {
            return _curIndex < _pathLength;
        }

        // Skip white space, one comma if allowed
        private static bool SkipWhiteSpace(bool allowComma)
        {
            var commaMet = false;
            while (More())
            {
                var ch = _pathString[_curIndex];
                switch (ch)
                {
                    case ' ':
                    case '\n':
                    case '\r':
                    case '\t': // SVG whitespace 
                        break;
                    case ',':
                        if (allowComma)
                        {
                            commaMet = true;
                            allowComma = false; // one comma only
                        }
                        else
                        {
                            ThrowBadToken();
                        }
                        break;
                    default:
                        // Avoid calling IsWhiteSpace for ch in (' ' .. 'z']
                        if (((ch > ' ') && (ch <= 'z')) || !Char.IsWhiteSpace(ch))
                        {
                            return commaMet;
                        }
                        break;
                }
                _curIndex++;
            }
            return commaMet;
        }

        private static void ThrowBadToken()
        {
            throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Unexpected character in path '{0}' at position {1}", _pathString, _curIndex - 1));
        }

        #endregion
    }
}